﻿<?php

	/**
	 * 
	 */
	class LoginHandler {
		
		private $db = NULL;
		public static $loggedin = "loggedin";
		public static $user = "user";				
		
		public function __construct(Database $database){
			$this->db = $database;
		} 
		
		/**
		 * Kontrollerar om man är inloggad
		 * @return boolean
		 */	
		public function IsLoggedIn(){
			if(isset($_SESSION[self::$loggedin])){
					return true;
			}
			return false;
		}
		
		/**
		 * Loggar in
		 * @param string användarnamn och lösenord
		 * @return boolean
		 */			
		public function DoLogin($username, $password){
				
			if (!isset($_SESSION[self::$loggedin])){
							
				$prep = $this->db->Prepare("SELECT (password) FROM user WHERE userName=?");
				$prep -> bind_param("s", $username);
				
				$storedPassword = $this->db->SelectOne($prep);
				
				if (crypt($password, $storedPassword) == $storedPassword){
					$_SESSION[self::$user] = $username;
					$_SESSION[self::$loggedin] = 1;	
					return true;
				}
				else
				return false;		
			}
			else 
			return false;
		}
		
		/**
		 * Loggar ut
		 */	
		public function DoLogout(){
			
			//session_destroy();?
			
			if (isset($_SESSION[self::$loggedin])){
				unset($_SESSION[self::$loggedin]);
				unset($_SESSION[self::$user]);	
			}
		}
		
		public function DeleteUser($userName){
			
			$prep = $this->db->Prepare("DELETE FROM user WHERE (userName=?)");
			$prep -> bind_param("s", $userName); 
			
			if($this->db->RunQuery($prep) == 1){
				return true;
			}					
			return false;
			
		}
	
				
	}
	


?>